<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once 'CS_Controller.php';
class BZ_Controller extends CI_Controller
{
    public $error;
    public $frontUser;
    public $uid; //用户UID
    public $userType;//用户类型
    public $userName;//用户名
    public $aliasName; //用户别名
    public $userTypeEn;
    public $userTypeName; //用户类型名称
    public $userParentId; //上级用户编号
    public $personalPhoto; //用户头像
    public $providerUid = 3578748;
    public $provider;
    public $data = ['headTitle' => '着想科技', 'provider' => '']; //视图data

    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache'); //加载缓存
        $this->load->helper('validation');
        $this->load->model('user_code_model', 'user_code');
        $this->load->model('tourism_provider_model','tourism_provider');

        $this->apiCommon(); //加载公用参数

        $this->_init(); //用着重载
        
        // 开发模式下开启性能分析
        if (ENVIRONMENT === 'development' || ENVIRONMENT === 'dev-security') {
            $this->output->enable_profiler(TRUE);
        }
    }
    
    public function _init() {}

    /**
     * 前置方法
     * 调用时的通用参数。
     */
    public function apiCommon()
    {
        $frontUser = get_cookie('frontUser');//获取已登录cookie值
        if ($frontUser) {
            $this->frontUser     = unserialize(preg_replace_callback( '!s:(\d+):"(.*?)";!s', function($m){return 's:'.strlen($m[2]).':"'.$m[2].'";';}, $frontUser));
            $this->uid           = $this->frontUser['ACT_UID']; //获取session uid
            $this->userType      = $this->frontUser['ACT_UTID']; //获取用户类型
            $this->userName      = $this->frontUser['OWNER_NAME']; //获取用户名
            $this->aliasName     = urldecode($this->frontUser['ALIAS_NAME']); //获取用户别名
            $this->userTypeEn    = $this->frontUser['ACT_TYPE']; //获取英文名
            $this->userTypeName  = urldecode($this->frontUser['ACT_TYPENAME']); //获取用户别名
            $this->userParentId  = $this->frontUser['PARENT_ID']; //获取上级用户编号
            $this->personalPhoto = urldecode($this->frontUser['PERSONAL_PHOTO']);
        }

        //获取供应商用户
        $providerUid = (int)$this->config->store_id; //获取store_id
        if ($providerUid) {
            $this->providerUid = $providerUid;
        }
        $provider = $this->tourism_provider->findOne(['uid' => $this->providerUid]);
        if ($provider->num_rows() > 0) {
            $this->provider = $provider->row();
            $this->data['headTitle'] = $this->provider->name;
            $this->data['provider']  = $this->provider;
        }
    }

    /**
     * 验证get参数，如果get参数有一个值不为空，则返回true
     * @param $params_get
     * @return bool
     */
    protected function search_get_validate($params_get)
    {
        $is_empty = false;
        if (is_array($params_get) && !empty($params_get)) {
            foreach ($params_get as $val) {
                if (!empty($val)) {
                    $is_empty = true;
                    break;
                }
            }
        }
        return $is_empty;
    }
    
    /**
     * 验证参数，如果参数有一个为空，则返回true
     * @param  $postData
     * @return boolean
     */
    protected function validateParam($postData)
    {
        $validate = false;
        if (is_array($postData)) { //验证checkbox，有一个不为空，则通过
            $is_empty = '';
            foreach ($postData as $val) {
                $is_empty .= $val;
            }
            if (empty($is_empty)) {
                $validate = true;
            }
        } else {
            if (empty($postData)) {
                $validate = true;
            }
        }
        return $validate;
    }
    
    /**
     * 程序执行错误跳转
     * @param 跳转路径 $url
     * @param url参数 $param
     * @param 提示信息 $message
     */
    protected function error($url, $param, $message)
    {
        if (is_array($message)) {
            foreach ($message as $val) {
                $this->error .= '<p>' . $val . '</p>';
            }
            $this->session->set_flashdata('error', $this->error);
        } else {
            $this->session->set_flashdata('error', $message);
        }
        
        $this->formatUrl($url, $param);
    }
    
    /**
     * 程序执行成功跳转
     * @param 跳转路径 $url
     * @param url参数  $param
     * @param 提示信息 $message
     */
    protected function success($url, $param, $message)
    {
        $this->session->set_flashdata('success', $message);
        $this->formatUrl($url, $param);
    }
    
    private function formatUrl($url, $param)
    {
        $len = strlen($url)-1;
        if ($url{$len} != '/') {
            $url = $url.'/';
        }
        
        if (is_array($param)) {
            $fullUrl = http_build_query($param);
            $url .= '?'.$fullUrl;
        } else {
            $url .= $param;
        }
        
        $parseUrl = parse_url($url);
        if ($parseUrl && isset($parseUrl['scheme'])) {
            $this->redirect($url);
        } else {
            $this->redirect($url);
        }
    }

    /**
     * 程序执行跳转
     * @param $url
     */
    protected function redirect($url)
    {
        redirectAction($url);
    }

    /**
     * json数据输出
     * @param $status
     * @param string $msg
     * @param array $data
     */
    protected function ajaxJson($status = true, $msg = '', $data = [])
    {
        if (is_array($status)) {
            echo json_encode($status, JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(array(
                'status' => $status,
                'msg'    => $msg,
                'data'   => $data
            ), JSON_UNESCAPED_UNICODE);
        }
        exit;
    }

    /**
     * js提交表单数据提示。
     * @param unknown $error
     * @param string $url
     */
    public function jsonMessage($error, $url='')
    {
        if (!empty($error)) {
            if (is_array($error)) {
                $json = array('status' => false, 'messages' => implode('\\n', $error));
            } else {
                $json = array('status' => false, 'messages' => $error);
            }
        } else {
            $json = array('status' => true, 'messages' => $url);
        }
        echo json_encode($json);exit;
    }
    
    /**
     * 错误回跳到首页
     * @param unknown $msg
     */
    protected function alertError($msg)
    {
        if (is_array($msg)) {
            $messages = implode('\\n', $msg);
        } else {
            $messages = $msg;
        }
        echo '<meta charset="utf-8"><script type="text/javascript">alert("'.$messages.'");location.href="'.site_url().'"</script>';exit;
    }
    
    /**
     * 错误回跳到首页
     * @param unknown $msg
     */
    protected function alertJumpPre($msg)
    {     
        if (is_array($msg)) {
            $messages = implode('\\n', $msg);
        } else {
            $messages = $msg;
        }
        echo '<meta charset="utf-8"><script type="text/javascript">alert("'.$messages.'");location.href="Javascript:window.history.go(-1)"</script>';exit;
    }

    /**
     * 分页get参数
     * @param $getParam
     * @return string
     */
    public function pageGetParam($getParam)
    {
        $suffix = '';
        if ($getParam) {
            $param = http_build_query($this->input->get());
            $suffix = '?'.$param;
        }
        return $suffix;
    }

    /**
     * ci 验证码
     * @param int $font_size
     * @param int $img_width
     * @param int $img_height
     * @param int $count
     * @return array
     */
    public function getCaptcha($font_size=20, $img_width=100, $img_height=30, $count=4)
    {
        $this->load->helper('captcha');
        $str = 'abcdefghgkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUXWXYZ23456789';
        $word = '';
        for ($i=0; $i < $count; $i++) {
            $word .= $str[mt_rand(0,strlen($str)-1)];
        }
        $vals = array(
            'word'       => $word,
            'img_path'   => $this->config->upload_image_path('', 'captcha'),
            'img_url'    => base_url('captcha').'/',
            'font_path'  => BASEPATH.'fonts/texb.ttf',
            'font_size'  => $font_size.'px',
            'img_width'  => $img_width,
            'img_height' => $img_height,
            'expiration' => '300'
        );
        $captcha = create_captcha($vals);
        set_cookie('captcha', $captcha['word'], 7200);
        return $captcha;
    }

    /**
     * $sms_type 1:56短信；2:第一短信平台;3:
     * @param $telephone
     * @param $content
     * @param int $sms_type
     * @return mixed
     */
    public function sendToSms($telephone, $content, $sms_type = 2)
    {
        $this->load->library('sms/sms', NULL, 'sms');
        return $this->sms->sendSms($telephone, $content, $sms_type);
    }

    /**
     * 阿里云短信验证码
     * @param string $mobile
     * @param string $aliTemp
     * @param array $params
     * @param string $type
     */
    public function sendCommonSms($mobile = '', $aliTemp = 'SMS_117170023', $params = [], $type = 'sms'/* call */)
    {
        $this->load->library('AliyunSms/AliSms', null, 'AliSms');
        $this->load->library('AliyunSms/AliCall', null, 'AliCall');

        $mobile = $mobile ? $mobile : $this->input->get_post('mobile_phone');
        if (!checkMobile($mobile)) {
            $this->ajaxJson(['status' => false, 'msg' => '手机号格式错误，请检查！']);
        }

        $code = mt_rand(100000, 999999);
        $sendTime = date('Y-m-d H:i:s');
        $endTime = date('Y-m-d H:i:s', strtotime('+10 minute'));

        $params = array_merge(['code' => $code], $params); //合并数组
        if ($type == 'call') {
            $res = AliCall::singleCallByTts($mobile, $aliTemp, $params);
        } else {
            $res = AliSms::sendSms($mobile, $aliTemp, $params);
        }
        if ($res['status']) {
            $result = $this->user_code->findOne(['mobile' => $mobile], 'id');
            if ($result->num_rows() > 0) {
                $status = $this->user_code->update(['code' => $code, 'send_time' => $sendTime, 'end_time' => $endTime], ['mobile' => $mobile]);
            } else {
                $status = $this->user_code->insert(['mobile' => $mobile, 'code' => $code, 'send_time' => $sendTime, 'end_time' => $endTime]);
            }
            if ($status) {
                $this->ajaxJson($res);
            } else {
                $this->ajaxJson(['status' => false, 'msg' => '网络繁忙，请稍后再试~']);
            }
        } else {
            $this->ajaxJson(['status' => false, 'msg' => '网络繁忙，请稍后再试~']);
        }
    }

    /**
     * 阿里云短信通知
     * @param string $mobile
     * @param string $aliTemp
     * @param array $params
     * @return array|mixed|SimpleXMLElement|stdClass
     */
    public function sendCommonSmsInfo($mobile = '', $aliTemp = 'SMS_117170023', $params = [])
    {
        $this->load->library('AliyunSms/AliSms', null, 'AliSms');

        $mobile = $mobile ? $mobile : $this->input->get_post('mobile_phone');
        if (!checkMobile($mobile)) {
            $this->ajaxJson(['status' => false, 'msg' => '手机号格式错误，请检查！']);
        }
        $res = AliSms::sendSms($mobile, $aliTemp, $params);

        return $res;
    }

    /**
     * 验证手机验证码
     * @param $mobile
     * @param $code
     * @return array
     */
    public function validateSmsInfo($mobile, $code)
    {
        $code    = $code ? $code : $this->input->post('code');
        $endTime = $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $mobile, 'code' => $code], 'id, end_time');//, 'end_time' => $endTime
        if ($result->num_rows() <= 0) {
            return ['status' => false, 'msg' => '手机验证码错误~'];
        }
        if ($result->row(0)->end_time < $endTime) {
            return ['status' => false, 'msg' => '手机验证码超过有效期，请重新获取~'];
        }

        return ['status' => true];
    }

    /**
     * 验证用户类型,如果是分销商(4096)，则返回true
     * @param int $userType 默认分销商
     * @return bool
     */
    public function validateUserType($userType = UTID_SELLER)
    {
        if ($this->userType&$userType) {
            return true;
        }
        return false;
    }

    /**
     * 验证用户登录类型
     * @param $usertype
     * @return array
     */
    public function usertype($usertype)
    {
        $userInfo = array();
        $bitusers= array(UTID_CUSTOMER, UTID_PROVIDER, UTID_TELLER, UTID_SELLER, UTID_GROWTH, UTID_MANAGER_L2, UTID_MANAGER_L1, UTID_BEIZHU, UTID_PURCHASER);
        foreach ($bitusers as $type) {
            if ((intval($type)& intval($usertype)) != intval($type)) {
                continue;
            }
            switch ($type) {
                case UTID_PROVIDER://供应商
                    $userInfo['type_en'] ='provider';
                    $userInfo['type_zh'] = '供应商';
                    break;
                case UTID_PURCHASER://采购
                    $userInfo['type_en'] = 'purchaser';
                    $userInfo['type_zh'] = '采购商';
                    break;
                case UTID_BEIZHU://着想保留
                    $userInfo['type_en'] = 'beizhu';
                    $userInfo['type_zh'] = '着想';
                    break;
                case UTID_MANAGER_L1://代理
                    $userInfo['type_en'] = 'manager_l1';
                    $userInfo['type_zh'] = '省级代理';
                    break;
                case UTID_MANAGER_L2:
                    $userInfo['type_en'] = 'manager_l2';
                    $userInfo['type_zh'] = '市级代理';
                    break;
                case UTID_GROWTH:
                    $userInfo['type_en'] = 'growth';
                    $userInfo['type_zh'] = '发展商';
                    break;
                case UTID_SELLER:
                    $userInfo['type_en'] = 'seller';
                    $userInfo['type_zh'] = '分销商';
                    break;
                case UTID_CUSTOMER:
                    $userInfo['type_en']  = 'customer';
                    $userInfo['type_zh']  = '会员';
                    break;
                case UTID_TELLER:
                    $userInfo['type_en'] = 'teller';
                    $userInfo['type_zh'] = '检票员';
                    break;
                case UTID_MAC:
                    $userInfo['type_en'] = 'mac';
                    $userInfo['type_zh'] = '终端机';
                default:
                    $userInfo['type_en'] = 'unknow';
                    $userInfo['type_zh'] = '未知用户类型';
                    break;
            }
        }
        return $userInfo;
    }
}